package com.yungee.controller;

import com.google.common.collect.Lists;
import com.yungee.logic.UploadFileLogic;
import com.yungee.model.PageData;
import com.yungee.util.FileUtil;
import com.yungee.util.StringUtils;
import com.yungee.vo.resp.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping(value = "/upload" ,produces={"application/json;charset=UTF-8"})
public class UploadFileController {


    @Autowired
    private UploadFileLogic uploadFileLogic;

    /**
     * 上传单个文件
     * @param file
     * @return
     */
    @PostMapping("/singleFile")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) {
        String url = uploadFileLogic.uploadFile(file);
        if (StringUtils.isNotEmpty(url)) {
            return AjaxResult.successData(url);
        } else {
            return AjaxResult.error("上传失败");
        }
    }

    /**
     * 上传多个文件
     */
    @PostMapping("/multiFile")
    public AjaxResult progressUploadFile(HttpServletRequest request) throws Exception {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
            return AjaxResult.error("不是文件上传请求");
        }
        DefaultMultipartHttpServletRequest defaultMultipartHttpServletRequest = (DefaultMultipartHttpServletRequest) request;
        List<MultipartFile> multipartFiles = defaultMultipartHttpServletRequest.getFiles("files");
        List<String> urls = Lists.newArrayList();
        for (MultipartFile multipartFile : multipartFiles) {
            String url = uploadFileLogic.uploadFile(multipartFile);
            if(StringUtils.isNotEmpty(url)){
                urls.add(url);
            }
        }
        return AjaxResult.success(urls);
    }

    /**
     * 列表查询
     * @param page
     * @param size
     * @return
     * @throws Exception
     */
    @GetMapping("/filePage")
    public AjaxResult filePage(int page,int size,String fileType) throws Exception {
        if (page <= 0){
            page = 1;
        }
        if (size <= 0){
            size = 10;
        }
        PageData pageData =uploadFileLogic.filePage(page,size,fileType);
        return AjaxResult.success(pageData);
    }
    /**
     * 删除文件
     * @param id
     * @return
     */
    @PostMapping("/deleteFile")
    public AjaxResult deleteFile(@RequestParam("id") Long id ) {
        boolean success =  uploadFileLogic.deleteFile(id);
        return AjaxResult.success(success);
    }
}
